package com.global.dao.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import com.global.dao.GridDao;
import com.global.model.Grid;
import com.global.model.Report;

@Repository("gridDao")
public class GridDaoImpl extends GenericDaoHibernate<Grid, Long> implements GridDao {

	public GridDaoImpl() {
		super(Grid.class);
	}
	
	/**
	 * {@inheritDoc}
	 */
	public Grid saveGrid(Grid grid) {
		if(grid!=null){
	        if (log.isDebugEnabled()) {
	            log.debug("gird's id: " + grid.getId());
	        }
	        getHibernateTemplate().saveOrUpdate(grid);
	        getHibernateTemplate().flush();
	        
	        grid = this.get(grid.getId());	        
		}
		
		return grid;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean saveBatchGrids(List<Grid> gridList) {
		if(gridList!=null){			
			getHibernateTemplate().saveOrUpdateAll(gridList);
			getHibernateTemplate().flush();
			
			return true;
		}
		
		return false;
	}
	
	/**
	 * {@inheritDoc}
	 */
	public Grid getGrid(String gridName) {
		if(StringUtils.isNotBlank(gridName)){
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
	        queryParams.put("uniqueGridName", gridName.toUpperCase());
			List<Grid> list = this.findByNamedQuery("findGridByName", queryParams);
			if(!list.isEmpty()){
				return list.get(0);
			}
		}

		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	public List<Grid> getGridList(Report report) {
		if(report!=null && report.getId()!=null){
			HashMap<String, Object> queryParams = new HashMap<String, Object>();
	        queryParams.put("reportId", report.getId());
			return this.findByNamedQuery("findGridByReport", queryParams);
		}

		return new ArrayList<Grid>();
	}

}
